﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DivaScriptConv;

namespace MikuMikuModel.DivaScriptConverter
{
    class DivaScriptConverter
    {
        static int currentWorker = 0;
        public static int maxWorker = 6;

        public static void ConvertDsc(string sourceFolder, string destinationFolder, bool replace, string pv_expr = "")
        {
            if (!Directory.Exists("dsc_json"))
            {
                Directory.CreateDirectory("dsc_json\\");
            }

            string[] files = System.IO.Directory.GetFiles(sourceFolder, "*.dsc", SearchOption.AllDirectories);
            foreach (var i in files)
            {
                if ((!File.Exists(destinationFolder + "\\" + Path.GetFileNameWithoutExtension(i) + ".dsc")) || (replace == true))
                {
                    while (currentWorker > maxWorker)
                    {
                        Thread.Sleep(33);
                    }
                    new Thread(() =>
                    {
                        bool expr = false;
                        var split = Path.GetFileNameWithoutExtension(i).Split('_');
                        string pvexp = "exp_PV" + split[1] + ".bin";

                        string[] arguments = new string[4];
                        if (File.Exists(pv_expr + pvexp))
                        {
                            arguments = new string[6];
                        }
                        arguments[0] = "-i:ft";
                        arguments[1] = i;

                        arguments[2] = "-o:a";
                        arguments[3] = Path.GetDirectoryName(destinationFolder) + "\\" + Path.GetFileNameWithoutExtension(i) + ".dsc";

                        //string arg = "-i:ft \"" + i + "\" -o:a " + Path.GetDirectoryName(destinationFolder) + "\\" + Path.GetFileNameWithoutExtension(i) + ".dsc";
                        if (File.Exists(pv_expr + pvexp))
                        {
                            //arg = arg + " -e " + pv_expr + pvexp;

                            arguments[4] = "-e";
                            arguments[5] = pv_expr + pvexp;
                            expr = true;
                        }
                        else
                        {

                        }
                        if (File.Exists("dbg"))
                        {
                            //DSC.json = true;
                        }
                        DSC.Convert(arguments);
                        //DivaScriptConv.Program.(arguments);

                        Logs.Logs.WriteLine("Converted - " + Path.GetFileName(i) + " " + pvexp + "=" + expr);
                        currentWorker--;
                    }).Start();
                    currentWorker++;
                }
            }
        }
    }
}
